package com.tuocent.dagv2.common.utils;

import com.tuocent.dagv2.constant.PublicConst;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.util.FileCopyUtils;

import javax.imageio.ImageIO;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.List;
import java.util.regex.Pattern;


@Component
public class PublicUtil {

    public static final String ZCE_KEYWORDS = "ARMZCE_";

    public static final String RANDOM_STR = "!@#$%^&*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    /**
     * 单位进位，中文默认为4位即（万、亿）
     */
    public static int UNIT_STEP = 4;

    /**
     * 单位
     */
    public static String[] CN_UNITS = new String[]{"个", "十", "百", "千", "万", "十",
            "百", "千", "亿", "十", "百", "千", "万"};

    /**
     * 汉字
     */
    public static String[] CN_CHARS = new String[]{"零", "一", "二", "三", "四",
            "五", "六", "七", "八", "九"};

    /**
     * 星期汉字
     */
    public static String[] CN_WEEK = new String[]{"一", "二", "三", "四",
            "五", "六", "日"};

    /**
     * 判断字符串是否是整数
     */
    public static boolean isInteger(String value) {
        try {
            Integer.parseInt(value);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 判断字符串是否为数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /*
     * 是否为浮点数？double或float类型。
     * @param str 传入的字符串。
     * @return 是浮点数返回true,否则返回false。
     */
    public static boolean isFloat(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
        return pattern.matcher(str).matches();
    }

    public static boolean isValidDate(String str) {
        boolean convertSuccess = true;
        // 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
            format.setLenient(false);
            format.parse(str);
        } catch (ParseException e) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            convertSuccess = false;
        }
        return convertSuccess;
    }

    public static boolean isValidDateTime(String str) {
        boolean convertSuccess = true;
        // 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
        SimpleDateFormat format = new SimpleDateFormat(PublicConst.DEFAULT_DATE_TIME_FORMAT);
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
            format.setLenient(false);
            format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            convertSuccess = false;
        }
        return convertSuccess;
    }

    //是否为整型日期
    public static boolean isIntDate(String str) {
        //如果字符串不等于8位数，侧为False;
        if (str.length() != 8) {
            return false;
        }
        //如果是8个0，通过
        if ("000000000".equals(str)) {
            return true;
        }
        String year = str.substring(0, 4);
        String month = str.substring(4, 6);
        String day = str.substring(6, 8);
        String tStr = year + "/" + month + "/" + day;
        if (!isValidDate(tStr)) {
            if (!isInteger(year) || !isInteger(month) || !isInteger(day)) {
                return false;
            }
            if (Integer.parseInt(month) > 13 || Integer.parseInt(month) < 0) {
                return false;
            }
            return Integer.parseInt(day) <= 31 && Integer.parseInt(month) >= 0;
        }
        return true;
    }

    /**
     * 检测年份是否正确
     *
     * @return boolean
     */
    public static boolean isIntYear(String str) {
        //如果字符串不等于4位数，侧为False;
        if ("".equals(str)) {
            return true;
        }
        String yearRole = "^\\d{4}$";
        return Pattern.matches(yearRole, str);
    }

    public static boolean isIntMonth(String str) {
        //如果字符串不等于2位数，侧为False;
        if ("".equals(str)) {
            return true;
        }
        if (str.length() != 2) {
            return false;
        }
        String yearMonth = "^(0?[0-9]|1[0-2])$";
        return Pattern.matches(yearMonth, str);
    }

    public static boolean isIntDay(String str) {
        if ("".equals(str)) {
            return true;
        }
        if (str.length() != 2) {
            return false;
        }
        //如果字符串不等于2位数，侧为False;
        String DayRole = "^((0?[0-9])|((1|2)[0-9])|30|31)$";
        return Pattern.matches(DayRole, str);
    }

    public static boolean isXmlDocument(String xml) {
        boolean flag = true;
        try {
            DocumentBuilderFactory foctory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = foctory.newDocumentBuilder();
            builder.parse(xml);
            flag = true;
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    //判断是否全部为全角字符
    public static boolean fullWidthString(String str) {
        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            String tempStr = String.valueOf(chars[i]);
            //判断是全角字符，如果不是，侧为有半角字符
            if (!tempStr.matches("[^\\x00-\\xff]")) {
                return false;
            }
        }
        return true;
    }


    public static String getRandomString(int len) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < len; i++) {
            int number = random.nextInt(62);
            sb.append(RANDOM_STR.charAt(number));
        }
        return sb.toString();
    }

    public static String convertOpe(String ope) {
        if (ope == null) {
            return "";
        }
        switch (ope) {
            case "gt":
                return "大于";
            case "ge":
                return "大于或等于";
            case "lt":
                return "小于";
            case "le":
                return "小于或等于";
            case "eq":
                return "等于";
            case "ne":
                return "不等于";
        }
        return "";
    }


    //转换成大写数字

    /**
     * 将阿拉伯数字转换为中文数字123=》一二三
     *
     * @param srcNum
     * @return
     */
    public static String getCNNum(int srcNum) {
        String desCNNum = "";

        if (srcNum <= 0)
            desCNNum = "零";
        else {
            int singleDigit;
            while (srcNum > 0) {
                singleDigit = srcNum % 10;
                desCNNum = CN_CHARS[singleDigit] + desCNNum;
                srcNum /= 10;
            }
        }

        return desCNNum;
    }

    /**
     * 数值转换为中文字符串 如2转化为贰
     */
    public String cvt(long num) {
        return this.cvt(num, false);
    }

    /**
     * 数值转换为中文字符串(口语化)
     *
     * @param num          需要转换的数值
     * @param isColloquial 是否口语化。例如12转换为'十二'而不是'一十二'。
     * @return
     */
    public String cvt(String num, boolean isColloquial) {
        int integer, decimal;
        StringBuffer strs = new StringBuffer(32);
        String[] splitNum = num.split("\\.");
        integer = Integer.parseInt(splitNum[0]);    //整数部分
        decimal = Integer.parseInt(splitNum[1]);    //小数部分
        String[] result_1 = convert(integer, isColloquial);
        for (String str1 : result_1)
            strs.append(str1);
        if (decimal == 0) {//小数部分为0时
            return strs.toString();
        } else {
            String result_2 = getCNNum(decimal);  //例如5.32，小数部分展示三二，而不是三十二
            strs.append("点");
            strs.append(result_2);
            return strs.toString();
        }
    }

    /*
     * 对于int,long类型的数据处理
     */
    public String cvt(long num, boolean isColloquial) {
        String[] result = convert(num, isColloquial);
        StringBuffer strs = new StringBuffer(32);
        for (String str : result) {
            strs.append(str);
        }
        return strs.toString();
    }

    /**
     * 用于求百分比方法，已考虑除数不为0的情况
     *
     * @param number1      除数
     * @param number2      被除数
     * @param formatNumber 保留几位小数
     * @return 百分比%
     */
    public static double getPercentage(double number1, double number2, int formatNumber) {
        double number100 = 0.0;
        if (number1 != 0 && number2 != 0) {
            double numberA = number1 / number2 * 100;//到报率求%
            number100 = new BigDecimal(numberA).setScale(formatNumber, RoundingMode.HALF_UP).doubleValue();//四舍五入保留2位小数
        }
        return number100;
    }

    /**
     * 将数值转换为中文
     *
     * @param num          需要转换的数值
     * @param isColloquial 是否口语化。例如12转换为'十二'而不是'一十二'。
     * @return
     */
    public static String[] convert(long num, boolean isColloquial) {
        if (num < 10) {// 10以下直接返回对应汉字
            return new String[]{CN_CHARS[(int) num]};// ASCII2int
        }

        char[] chars = String.valueOf(num).toCharArray();
        if (chars.length > CN_UNITS.length) {// 超过单位表示范围的返回空
            return new String[]{};
        }

        boolean isLastUnitStep = false;// 记录上次单位进位
        ArrayList<String> cnchars = new ArrayList<String>(chars.length * 2);// 创建数组，将数字填入单位对应的位置
        for (int pos = chars.length - 1; pos >= 0; pos--) {// 从低位向高位循环
            char ch = chars[pos];
            String cnChar = CN_CHARS[ch - '0'];// ascii2int 汉字
            int unitPos = chars.length - pos - 1;// 对应的单位坐标
            String cnUnit = CN_UNITS[unitPos];// 单位
            boolean isZero = (ch == '0');// 是否为0
            boolean isZeroLow = (pos + 1 < chars.length && chars[pos + 1] == '0');// 是否低位为0

            boolean isUnitStep = (unitPos >= UNIT_STEP && (unitPos % UNIT_STEP == 0));// 当前位是否需要单位进位

            if (isUnitStep && isLastUnitStep) {// 去除相邻的上一个单位进位
                int size = cnchars.size();
                cnchars.remove(size - 1);
                if (!CN_CHARS[0].equals(cnchars.get(size - 2))) {// 补0
                    cnchars.add(CN_CHARS[0]);
                }
            }

            if (isUnitStep || !isZero) {// 单位进位(万、亿)，或者非0时加上单位
                cnchars.add(cnUnit);
                isLastUnitStep = isUnitStep;
            }
            if (isZero && (isZeroLow || isUnitStep)) {// 当前位为0低位为0，或者当前位为0并且为单位进位时进行省略
                continue;
            }
            cnchars.add(cnChar);
            isLastUnitStep = false;
        }

        Collections.reverse(cnchars);
        // 清除最后一位的0
        int chSize = cnchars.size();
        String chEnd = cnchars.get(chSize - 1);
        if (CN_CHARS[0].equals(chEnd) || CN_UNITS[0].equals(chEnd)) {
            cnchars.remove(chSize - 1);
        }

        // 口语化处理
        if (isColloquial) {
            String chFirst = cnchars.get(0);
            String chSecond = cnchars.get(1);
            if (chFirst.equals(CN_CHARS[1]) && chSecond.startsWith(CN_UNITS[1])) {// 是否以'一'开头，紧跟'十'
                cnchars.remove(0);
            }
        }
        return cnchars.toArray(new String[]{});
    }

    public static String BegNumberStr(String str) {
        int num = 0;
        num = Integer.parseInt(str);
        StringBuffer s = new StringBuffer();
        for (String string : convert(num, true)) {
            s.append(string);
        }
        return s.toString();
    }


    /**
     * MAP 排序
     *
     * @param map
     * @return
     */
    public static Map<String, Integer> sortMap(Map<String, Integer> map) {
        if (map == null) return null;
        //利用Map的entrySet方法，转化为list进行排序
        List<Map.Entry<String, Integer>> entryList = new ArrayList<>(map.entrySet());
        //利用Collections的sort方法对list排序
        Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                //正序排列，倒序反过来
                return o1.getValue() - o2.getValue();
            }
        });
        //遍历排序好的list，一定要放进LinkedHashMap，因为只有LinkedHashMap是根据插入顺序进行存储
        LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<String, Integer>();
        for (Map.Entry<String, Integer> e : entryList
        ) {
            linkedHashMap.put(e.getKey(), e.getValue());
        }
        return linkedHashMap;
    }

    public static String getMillisToTime(long size) {
        StringBuffer bytes = new StringBuffer();
        DecimalFormat format = new DecimalFormat("###.##");
        if (size >= 1000 * 60 * 60) {
            double i = (size / (1000 * 60 * 60));
            bytes.append(format.format(i)).append("小时");
        } else if (size >= 1000 * 60) {
            double i = (size / (1000 * 60));
            bytes.append(format.format(i)).append("分");
        } else if (size >= 1000) {
            double i = (size / (1000));
            bytes.append(format.format(i)).append("秒");
        } else {
            bytes.append(size + "豪秒");
        }
        return bytes.toString();
    }

    /**
     * 把byte转化为KB、MB、GB
     *
     * @param size
     * @return
     */
    public static String getNetFileSizeDescription(long size) {
        StringBuffer bytes = new StringBuffer();
        DecimalFormat format = new DecimalFormat("###.00");
        if (size >= 1024L * 1024L * 1024L * 1024L) {
            double i = (size / (1024.0 * 1024.0 * 1024.0 * 1024.0));
            bytes.append(format.format(i)).append("TB");
        } else if (size >= 1024L * 1024L * 1024L) {
            double i = (size / (1024.0 * 1024.0 * 1024.0));
            bytes.append(format.format(i)).append("GB");
        } else if (size >= 1024L * 1024L) {
            double i = (size / (1024.0 * 1024.0));
            bytes.append(format.format(i)).append("MB");
        } else if (size >= 1024L) {
            double i = (size / (1024.0));
            bytes.append(format.format(i)).append("KB");
        } else if (size < 1024L) {
            bytes.append("0B");
        }
        return bytes.toString();
    }

    public static int getTextLength(String text) {
        int textLength = text.length();
        int length = textLength;
        for (int i = 0; i < textLength; i++) {
            if (String.valueOf(text.charAt(i)).getBytes().length > 1) {
                length++;
            }
        }
        return (length % 2 == 0) ? length / 2 : length / 2 + 1;
    }

    public static InputStream imageWaterMark(File file, String filetype, String waterMarkText) {
        InputStream in = null;
        String fontName = "宋体";
        int fontStyle = Font.TRUETYPE_FONT;
        Color color = new Color(7, 7, 8);
        Integer degree = -30;
        float alpha = (float) 0.3;
        //读取指定路径下面的文件
        try {
            Image srcImg = ImageIO.read(file);
            int imgWidth = srcImg.getWidth(null);
            int imgHeight = srcImg.getHeight(null);
            BufferedImage buffImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
            // 得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 设置对线段的锯齿状边缘处理
            // g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), 0, 0, null);
            // 设置水印文字大小
            int fontSize = buffImg.getWidth(null) / 300 * 6;
            // 设置水印Font
            g.setFont(new Font(fontName, fontStyle, fontSize));
            // 设置水印文字颜色
            g.setColor(color);
            // 设置水印旋转
            if (null != degree) {
                g.rotate(Math.toRadians(degree), (double) imgWidth / 2, (double) imgHeight / 2);
            }
            double h = imgHeight * Math.sin(degree);
            int xStart = (int) Math.sqrt(Math.pow(h, 2) / 2);
            // 设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

            // 计算水印文字的大小
            int textWidth = fontSize * PublicUtil.getTextLength(waterMarkText);
            int textHeight = fontSize;
            // 循环打印多个水印
            for (int y = -imgHeight; y < imgHeight * 2; y += textHeight + fontSize * 6) {
                for (int x = -xStart; x < imgWidth * 2; x += textWidth + fontSize * 3 / 2) {
                    // 笫一参数-> 设置的内容,后面两个参数->文字在图片上的坐标位置
                    g.drawString(waterMarkText, x, y);
                }
            }
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
            // 释放资源
            g.dispose();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(buffImg, filetype, os);
            in = new ByteArrayInputStream(os.toByteArray());
        } catch (IOException e) {
        }
        return in;
    }

    public static BufferedImage imageWaterMark(BufferedImage buffImg, String waterMarkText) throws IOException {
        InputStream in = null;
        String fontName = "宋体";
        int fontStyle = Font.TRUETYPE_FONT;
        Color color = new Color(7, 7, 8);
        Integer degree = -30;
        float alpha = (float) 0.3;
        //读取指定路径下面的文件
        int imgWidth = buffImg.getWidth();
        int imgHeight = buffImg.getHeight();
        // 得到画笔对象
        Graphics2D g = buffImg.createGraphics();
        // 设置对线段的锯齿状边缘处理
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(buffImg.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), 0, 0, null);
        // 设置水印文字大小
        int fontSize = buffImg.getWidth(null) / 300 * 6;
        // 设置水印Font
        g.setFont(new Font(fontName, fontStyle, fontSize));
        // 设置水印文字颜色
        g.setColor(color);
        // 设置水印旋转
        if (null != degree) {
            g.rotate(Math.toRadians(degree), (double) imgWidth / 2, (double) imgHeight / 2);
        }
        double h = imgHeight * Math.sin(degree);
        int xStart = (int) Math.sqrt(Math.pow(h, 2) / 2);
        // 设置水印文字透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

        // 计算水印文字的大小
        int textWidth = fontSize * PublicUtil.getTextLength(waterMarkText);
        int textHeight = fontSize;
        // 循环打印多个水印
        for (int y = -imgHeight; y < imgHeight * 2; y += textHeight + fontSize * 6) {
            for (int x = -xStart; x < imgWidth * 2; x += textWidth + fontSize * 3 / 2) {
                // 笫一参数-> 设置的内容,后面两个参数->文字在图片上的坐标位置
                g.drawString(waterMarkText, x, y);
            }
        }
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        // 释放资源
        g.dispose();
/*
        OutputStream os = null;
        os = new FileOutputStream ("d:/ee.jpg");
        ImageIO.write (buffImg, "JPG", os);
*/
        //ByteArrayOutputStream os = new ByteArrayOutputStream();
        //ImageIO.write(buffImg, "JPG", os);
        //in=new ByteArrayInputStream(os.toByteArray());
        return buffImg;
    }

    public static long getFilesCount(File srcFile, String ext, Boolean countSub) {
        long count = 0;
        // 把所有目录、文件放入数组
        File[] files = srcFile.listFiles();
        // 遍历数组每一个元素
        for (File f : files) {
            // 判断元素是不是文件夹，是文件夹就重复调用此方法（递归）
            if (f.isDirectory()) {
                if (countSub) {
                    count = count + getFilesCount(f, ext, countSub);
                }
            } else {
                // 判断文件是不是以ext结尾的文件，并且count++（注意：文件要显示扩展名）
                if (!"".equals(ext)) {
                    if (f.getName().endsWith(ext)) {
                        count++;
                    }
                } else {
                    count++;
                }
            }
        }
        return count;
    }

    public static List<String> getFilesList(File srcFile, String ext) {
        List<String> list = new ArrayList<>();
        File[] files = srcFile.listFiles();
        for (File f : files) {
            // 判断元素是不是文件夹，是文件夹就重复调用此方法（递归）
            if (!f.isDirectory()) {
                if (!"".equals(ext)) {
                    if (f.getName().endsWith(ext)) {
                        list.add(f.getName());
                    }
                } else {
                    list.add(f.getName());
                }
            }
        }
        return list;
    }

    /**
     * 增加天数
     *
     * @param day
     * @return
     */
    public static LocalDate plusDay(int day) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        ca.add(Calendar.DATE, day);// num为增加的天数，可以改变的
        return ca.getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    /**
     * 创建单号
     *
     * @return
     */
    public static String createNewBidNumber(String front) {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(currentTime);
        String random = RandomStringUtils.randomNumeric(3);
        return front + dateString + random;
    }

    /**
     * 文件转为二进制数组
     *
     * @param file
     * @return
     */
    public static byte[] fileToBinArray(File file) {
        try {
            InputStream fis = new FileInputStream(file);
            byte[] bytes = FileCopyUtils.copyToByteArray(fis);
            return bytes;
        } catch (Exception ex) {
            throw new RuntimeException("transform file into bin Array 出错", ex);
        }
    }

    public static String encodeBase64File(String path) {
        try {
            File file = new File(path);
            FileInputStream inputFile = new FileInputStream(file);
            byte[] buffer = new byte[inputFile.available()];
            inputFile.read(buffer);
            inputFile.close();
            Base64.Encoder encoder = Base64.getEncoder();
            return encoder.encodeToString(buffer);
        } catch (Exception ex) {
            throw new RuntimeException("transform file into Base64 出错", ex);
        }
    }

    /**
     * 将base64字符解码保存文件
     *
     * @param base64Code base64字符串
     * @param targetPath 文件地址
     * @throws Exception
     */
    public static void decodeBase64File(String base64Code, String targetPath) throws Exception {
        File file = new File(targetPath);
        if (!file.getParentFile().exists()) {
            file.mkdirs();
        }
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] buffer = decoder.decode(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }

    /**
     * 检测是否为页号
     *
     * @param pageCode
     * @return
     */
    public static boolean checkPageCode(String pageCode, long sPage, long ePage) {
        String p = "^[1-9]\\d-[1-9]\\d$";
        if (!pageCode.matches(p)) {
            return false;
        }
        String[] pages = pageCode.split("-");
        return sPage == Long.parseLong(pages[0]) && ePage == Long.parseLong(pages[0]);
    }

    public static long getIntStr(String str) {
        long value = 0L;
        if (str == null) {
            return value;
        }
        int len = str.length();
        // str.charAt(i) 方法回去检查下标的合法性，一般先转换成字符数组
        char[] charArray = str.toCharArray();
        int index = 0;

        while (index < len) {
            if ("0".equals(charArray[index])) {
                index++;
                continue;
            }
            String res = String.valueOf(charArray[index]);
            if (!isInteger(res)) {
                break;
            }
            value = value * 10 + Long.valueOf(res);
            index++;
        }
        return value;
    }

    public static String getFileMd5(String file) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(file);
        long size = fileInputStream.available();
        byte[] bf;
        if (size > PublicConst.MD5CheckSize) {
            bf = new byte[PublicConst.MD5CheckSize];
        } else {
            bf = new byte[(int) size];
        }
        try {
            fileInputStream.read(bf);
            String md5 = DigestUtils.md5DigestAsHex(bf);
            fileInputStream.close();
            return md5;
        } catch (Exception E) {
            return "";
        }
    }


    public static void delFile(File index) {
        if (index.isDirectory()) {
            File[] files = index.listFiles();
            for (File in : files) {
                delFile(in);
            }
        }
        index.delete();
    }

    public static String getContentType(String ext) {
        //判断文件格式, 设置相应的输出文件格式
        return switch (ext.toLowerCase()) {
            case "jpg" -> "image/jpeg";
            case "png" -> "image/png";
            case "pdf" -> "application/pdf";
            default -> "multipart/form-data";
        };
    }

    public static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        CellType cellType = cell.getCellType();
        switch (cellType) {
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    Date d = DateUtil.getJavaDate(cell.getNumericCellValue());
                    SimpleDateFormat f = new SimpleDateFormat(PublicConst.DEFAULT_DATE_TIME_FORMAT);
                    return f.format(d);
                } else {
                    cell.setCellType(CellType.STRING);
                    return org.apache.commons.lang3.StringUtils.trimToEmpty(cell.getStringCellValue());
                }
            case STRING:
                return cell.getStringCellValue();
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            case BLANK:
                return "";
            case ERROR:
                return String.valueOf(cell.getErrorCellValue());
            default:
                return StringUtils.EMPTY;
        }
    }

}
